import { Injectable, NotFoundException } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { InjectRepository } from '@nestjs/typeorm'
import * as tencentcloud from 'tencentcloud-sdk-nodejs'
import { Repository } from 'typeorm'
import { asrRegToken, IAsrConfig } from '~/config/asr.config'
import { AsrQueryDto } from '../dto/asr-query.dto'
import { CreateAsrTaskDto } from '../dto/create-asr-task.dto'
import { AsrTaskEntity } from '../entities/asr-task.entity'
import { AsrTaskPaginationResult, AsrTaskResult, AsrTaskStatus, AsrTaskType, TencentAsrResponse } from '../interfaces/asr.interface'

@Injectable()
export class AsrService {
  private readonly asrConfig: IAsrConfig

  constructor(
    private readonly configService: ConfigService,
    @InjectRepository(AsrTaskEntity)
    private readonly asrTaskRepository: Repository<AsrTaskEntity>,
  ) {
    this.asrConfig = this.configService.get(asrRegToken)
  }

  /**
   * 创建腾讯云ASR任务
   */
  async createTencentAsrTask(createAsrTaskDto: CreateAsrTaskDto): Promise<AsrTaskResult> {
    const { url, taskType = AsrTaskType.TENCENT } = createAsrTaskDto

    // 创建任务记录
    const asrTask = this.asrTaskRepository.create({
      url,
      taskType,
      status: AsrTaskStatus.NOT_STARTED,
    })
    await this.asrTaskRepository.save(asrTask)

    try {
      // 调用腾讯云ASR接口创建任务
      const AsrClient = tencentcloud.asr.v20190614.Client
      const clientConfig = {
        credential: {
          secretId: this.asrConfig.accessKeyId,
          secretKey: this.asrConfig.accessKeySecret,
        },
        region: 'ap-guangzhou', // 根据实际需求设置区域
        profile: {
          httpProfile: {
            endpoint: 'asr.tencentcloudapi.com',
          },
        },
      }

      const client = new AsrClient(clientConfig)
      const params = {
        EngineModelType: '16k_zh', // 中文普通话通用，根据实际需求配置
        ChannelNum: 1,
        ResTextFormat: 0,
        SourceType: 0,
        Url: url,
      }

      // 调用腾讯云接口创建识别任务
      const data = await client.CreateRecTask(params) as TencentAsrResponse

      // 更新任务状态和任务ID
      await this.asrTaskRepository.update(asrTask.id, {
        taskId: data.TaskId,
        status: AsrTaskStatus.PROCESSING,
      })

      return {
        id: asrTask.id,
        taskId: data.TaskId,
        url,
        status: AsrTaskStatus.PROCESSING,
      }
    }
    catch (error) {
      // 更新任务状态为失败
      await this.asrTaskRepository.update(asrTask.id, {
        status: AsrTaskStatus.FAILED,
      })

      throw new Error(`创建ASR任务失败: ${error.message}`)
    }
  }

  /**
   * 根据ID查询ASR任务
   */
  async findById(id: number): Promise<AsrTaskEntity> {
    const task = await this.asrTaskRepository.findOne({ where: { id, isDelete: 0 } })
    if (!task) {
      throw new NotFoundException(`ID为${id}的ASR任务不存在`)
    }
    return task
  }

  /**
   * 根据任务ID查询ASR任务
   */
  async findByTaskId(taskId: string): Promise<AsrTaskEntity> {
    const task = await this.asrTaskRepository.findOne({ where: { taskId, isDelete: 0 } })
    if (!task) {
      throw new NotFoundException(`任务ID为${taskId}的ASR任务不存在`)
    }
    return task
  }

  /**
   * 查询ASR任务列表
   */
  async findAll(query: AsrQueryDto): Promise<AsrTaskPaginationResult> {
    const { page = 1, pageSize = 10, url, taskId, taskType, status } = query

    // 构建查询条件
    const whereConditions: any = { isDelete: 0 }

    if (url) {
      whereConditions.url = url
    }

    if (taskId) {
      whereConditions.taskId = taskId
    }

    if (taskType !== undefined) {
      whereConditions.taskType = taskType
    }

    if (status !== undefined) {
      whereConditions.status = status
    }

    // 查询总数
    const total = await this.asrTaskRepository.count({ where: whereConditions })

    // 查询分页数据
    const items = await this.asrTaskRepository.find({
      where: whereConditions,
      skip: (page - 1) * pageSize,
      take: pageSize,
      order: { createdAt: 'DESC' },
    })

    return {
      items,
      total,
      page,
      pageSize,
    }
  }
}
